/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language enrstuing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.enrstu.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.enrstu.service.AdministrativeDivisionService;
import me.zhengjie.modules.enrstu.service.CommunityService;
import me.zhengjie.modules.enrstu.service.dto.AdministrativeDivisionImportDto;
import me.zhengjie.modules.enrstu.service.dto.CommunityDto;
import me.zhengjie.modules.enrstu.service.dto.SchoolDto;
import me.zhengjie.modules.enrstu.domain.Community;
import me.zhengjie.modules.enrstu.repository.CommunityRepository;
import me.zhengjie.modules.enrstu.service.SchoolService;
import me.zhengjie.modules.enrstu.service.mapstruct.CommunityMapper;
import me.zhengjie.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author yyx
* @date 2024-10-23
**/
@Service("communityServiceImpl")
@RequiredArgsConstructor
@Slf4j
public class CommunityServiceImpl implements CommunityService{
    private final CommunityRepository communityRepository;
    private final CommunityMapper communityMapper;
    private final AdministrativeDivisionService administrativeDivisionCommonService;

    @Override
    @Transactional
    public CommunityDto findById(String communityId) {
        Community community = communityRepository.findById(communityId).orElseGet(Community::new);
        ValidationUtil.isNull(community.getCommunityId(),"Community","communityId",communityId);
        return communityMapper.toDto(community);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Community resources,List<Community> communitylist) {

        if (!ObjectUtil.isNull(resources.getCommunityName())){
            resources.setCommunityId(IdUtil.simpleUUID());
            communityRepository.save(resources);
        }
        if (!communitylist.isEmpty()){
            log.info("批量插入社区数据：{}",communitylist);
            communityRepository.saveAll(communitylist);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Community resources) {
        Community community = communityRepository.findById(resources.getCommunityId()).orElseGet(Community::new);
        ValidationUtil.isNull( community.getCommunityId(),"Community","id",resources.getCommunityId());
        community.copy(resources);
        communityRepository.save(community);
    }

    @Override
    @Transactional
    public void delete(String id) {
        CommunityDto byId = this.findById(id);
        communityRepository.deleteById(byId.getCommunityId());
    }

    @Override
    public void download(List<CommunityDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CommunityDto community : all) {
            Map<String,Object> map = new LinkedHashMap<>();

            map.put("学区id", community.getDistrictId());
            map.put("社区名称", community.getCommunityName());
            map.put("创建时间戳", community.getGmtCreate());
            map.put("更新时间戳", community.getGmtModified());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 根据学区id统计相关的社区总数
     * @param id /
     * @return /
     */
    @Override
    public Long total(String id) {
        log.info("根据学区id查询对应学校的总人数！id{}:人数{}",id,communityRepository.countByDistrictId(id));
        return communityRepository.countByDistrictId(id);

    }


    @Override
    public List<Object> queryAll(String id) {
        return communityRepository.findAllByDistrictId(id).stream().map(
                community -> {
                    CommunityDto communityDto = new CommunityDto();
                    communityDto.setCommunityId(community.getCommunityId());
                    communityDto.setCommunityName(community.getCommunityName());
                    return communityDto;
                }
        ).collect(Collectors.toList());
    }



    @Override
    public Boolean isCommunityName(String name) {
        return communityRepository.existsByCommunityName(name);
    }

    @Override
    public void updateSave(String id, Object obj) {
        Community community = communityRepository.findById(id).orElseGet(Community::new);
        ValidationUtil.isNull( community.getCommunityId(),"Community","id",id);
        community.setCommunityName((String)obj);
        communityRepository.save(community);
    }

    @Override
    public void createSaveBatch(List<AdministrativeDivisionImportDto> communitylist, String schoolDistrictId) {
        log.info("communitylist：{}",communitylist);
        List<String> communityNames = administrativeDivisionCommonService.filterInvalidAdministrativeDivision(communitylist);
        List<Community> communityNameList = communityNames.stream()
                .filter(communityName -> !communityRepository.existsByCommunityName(communityName))
                .map(communityName -> {
                    Community communityBash = new Community();
                    communityBash.setCommunityName(communityName);
                    communityBash.setDistrictId(schoolDistrictId);
                    communityBash.setCommunityId(IdUtil.simpleUUID());
                    return communityBash;
                }).collect(Collectors.toList());
        communityRepository.saveAll(communityNameList);
    }




}